package com.mars.miaosha.service;

import com.mars.miaosha.dao.MiaoshaUserDao;
import com.mars.miaosha.domain.MiaoshaUser;
import com.mars.miaosha.exception.GlobalException;
import com.mars.miaosha.redis.RedisService;
import com.mars.miaosha.redis.UserKey;
import com.mars.miaosha.result.CodeMsg;
import com.mars.miaosha.util.MD5Util;
import com.mars.miaosha.util.UUIDUtil;
import com.mars.miaosha.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author MARS
 * @date 2018/5/8
 */

@Service
public class MiaoshaUserService {
    public static final String COOKIE_NAME_TOKEN = "token";

    @Autowired
    private MiaoshaUserDao miaoshaUserDao;
    @Autowired
    private RedisService redisService;

    public MiaoshaUser getById(long id){
       return miaoshaUserDao.getById(id);
    }

    public boolean login(HttpServletResponse response, LoginVo loginVo) {
        if(loginVo == null){
            // 业务代码出现异常向上抛出
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        // 判断用户是否存在
        MiaoshaUser user = getById(Long.parseLong(mobile));
        if (user == null ){
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }

        // 验证用户密码
        String dbPassword = user.getPassword();
        String salt = user.getSalt();
        String p = MD5Util.formPassToDBPass(password,salt);
        if (!p.equals(dbPassword)) {
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }

        //  // 登录成功后操作,添加cookie
        // 1.生成cookie
        String token = UUIDUtil.getUUID();
        addCookie(response,token,user);

        return true;
    }


    private void addCookie(HttpServletResponse response,String token,MiaoshaUser user){

        // 2.将用户信息存在redis缓存中(key:token,vlaue:用户信息)
        redisService.set(UserKey.token,token,user);
        // 3.生成cookie
        Cookie cookie = new Cookie(COOKIE_NAME_TOKEN,token);
        // 设置cookie的过期时间
        cookie.setMaxAge(UserKey.token.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 根据token 获取User信息
     * @param token
     * @return
     */
    public MiaoshaUser getByToken(HttpServletResponse response,String token) {
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        MiaoshaUser user = redisService.get(UserKey.token,token,MiaoshaUser.class);
        // 延长token的有效期，重新设置cookie，再返回给浏览器
        // 判断用户
        if (user!=null){
            addCookie(response,token,user);
        }
        return user;

    }
}
